package com.qzdatasoft.mcp.demo.client;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.boot.CommandLineRunner;

import java.util.Scanner;

//@Service
public class PredefinedQuestions implements CommandLineRunner {

    private SyncMcpToolCallbackProvider toolCallbackProvider;

    private final OpenAiChatModel model;

    public PredefinedQuestions(OpenAiChatModel model, SyncMcpToolCallbackProvider toolCallbackProvider) {
        this.model = model;
        this.toolCallbackProvider = toolCallbackProvider;
    }
    private static final String DEFAULT_PROMPT = "你是一个聊天助手，请根据用户提问回答！";
    @Override
    public void run(String... args) throws Exception {
        ChatClient chatClient = ChatClient.create(model);
        ToolCallback[] toolCallbacks = toolCallbackProvider.getToolCallbacks();
        // 创建Scanner对象用于接收用户输入
        Scanner scanner = new Scanner(System.in);
        System.out.println(">>> 欢迎使用问答系统！输入'exit'退出程序。");

        while (true) {
            // 提示用户输入问题
            System.out.print("\n>>> QUESTION: ");
            String userInput = scanner.nextLine();

            // 如果用户输入"exit"，则退出循环
            if ("exit".equalsIgnoreCase(userInput)) {
                System.out.println(">>> 已退出问答系统。");
                break;
            }

            String responseStr = chatClient
                    .prompt(userInput)
                    .toolCallbacks(toolCallbacks)
                    .tools(new DateTimeTools())
                    .call()
                    .content();

            try {
                System.out.println("\n>>> ASSISTANT: " + responseStr);
            } catch (Exception e) {
                System.out.println("\n>>> ERROR: 无法处理您的请求，请稍后再试。");
                e.printStackTrace();
            }
        }

        scanner.close();
    }

}
